<template>
  <div class="app-container">
    <el-container>
      <el-header>
        选择账号:
        <el-select v-model="wc_id" placeholder="请选择" @change="handelChangeAccount">
          <el-option
            v-for="item in wcconfigs"
            :key="item.id"
            :label="item._serialized"
            :value="item.id"
          />
        </el-select>
        <el-select v-model="query_follow_status" placeholder="请选择跟进状态">
          <el-option
            v-for="item in follow_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-cascader
          v-model="cascaderValue"
          :options="orderStates"
          :props="{ checkStrictly: true , value: 'id', label: 'name', expandTrigger: 'hover'}"
          clearable
          @change="handleChangeState"
        />

        <el-input-number v-model="chatLimit" :min="20" :max="100" placeholder="最大刷新话题数" style="width:150px; display: inline-block;" />
        <el-input v-model="searchQuery" placeholder="输入名称/号码过滤对话" style="width: 300px;display: inline-block;" />
        <el-button style="margin-right: 10px" :loading="loadingchats" @click="handleGetChat">刷新</el-button>
      </el-header>
      <el-container>
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="6" class="chat-sidebar-wrapper">
            <div v-if="!isMobile" class="chat-sidebar">
              <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="全部对话" name="all" />
                <el-tab-pane label="未回复" name="unreplied" />
              </el-tabs>
              <div class="chat-list">
                <div
                  v-for="chat in sortedChats"
                  :key="chat._serialized"
                  class="chat-item"
                  :class="{ 'active': current_chat._serialized === chat._serialized }"
                  @click="handleChangChat(chat._serialized)"
                >
                  <div class="chat-item-content">
                    <div class="chat-avatar-wrapper">
                      <el-image v-if="chat.avatar" class="chat-avatar" :src="chat.avatar" />
                    </div>
                    <div class="chat-info">
                      <div class="chat-name">
                        <i v-if="chat.is_pin" :class="[chat.is_pin ? 'el-icon-star-on' : 'el-icon-star-off', { 'is-pinned': chat.is_pin }]" style="color: goldenrod;" />
                        {{ chat.nickname || chat.name }}
                        <span v-if="chat.customer !== ''">{{ chat.customer.crmcustomercategory__name }}</span>
                      </div>
                      <div v-if="chat.customer !== '' && chat.customer.orders.length" class="chat-last-message">{{ chat.customer.orders[0].name }}</div>
                    </div>
                    <div class="chat-meta">
                      <span class="chat-time">{{ chat.lastmessage_at_short }}</span>
                      <el-badge v-if="chat.unreadCount" :value="chat.unreadCount" class="unread-badge" />
                      <el-popover
                        v-if="chat.customer !== '' && chat.customer.orders.length"
                        placement="top-start"
                        :title="chat.customer.name"
                        width="400"
                        trigger="hover"
                      >
                        <el-table :data="chat.customer.orders">
                          <el-table-column width="100" property="order_no" label="订单编号" />
                          <el-table-column property="name" label="订单" />
                          <el-table-column property="crmorderstate_name" label="订单状态" />
                        </el-table>
                        <el-button slot="reference" type="text" style="float: right;align-content: center;font-size: xx-small"><i class="el-icon-s-custom" :style="'color:' + chat.crmorderstate_color" />{{ chat.customer.orders[0].crmorderstate_name }}</el-button>

                      </el-popover>
                    </div>
                  </div>
                </div>
                <!--                 <el-button v-if="total_chats > whatsappChats.length" @click="handleGetChat" class="show-more-btn">-->
                <!--                  加载更多 ({{ total_chats }})-->
                <!--                </el-button>-->
                <!--                 <el-button v-else @click="handleGetChat" class="show-more-btn">-->
                <!--                  所有数据总共 ({{ total_chats }})-->
                <!--                </el-button>-->
                <el-button v-if="hasMoreChats" class="show-more-btn" @click="handleLoadMoreChats">
                  加载更多 (剩余 {{ remainingChatsCount }})
                </el-button>
                <el-button v-else class="show-more-btn" disabled>
                  已加载全部 (共 {{ total_chats }})
                </el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <el-container style="max-width: 640px; border: black;border-top: 1px solid #dbdbdb;border-right: 1px solid #dbdbdb;">
              <div v-if="current_chat !== ''" class="chat-header">
                <div>{{ current_chat._serialized }}</div>
                <el-button
                  type="text"
                  :title="current_chat.is_pin ? '取消置顶' : '置顶'"
                  class="pin-button"
                  @click.stop="togglePin(current_chat)"
                >
                  <i :class="[current_chat.is_pin ? 'el-icon-star-on' : 'el-icon-star-off', { 'is-pinned': current_chat.is_pin }]" />
                </el-button>
                <el-button v-if="current_chat.customer === ''" title="绑定客户" style="float: right; margin-right: 10px" size="mini" @click="handleBindCustomer(current_chat)"><i class="el-icon-user" /></el-button>
                <div v-else>
                  <!--                   <a title="点击查看客户信息" @click="handleShowCustomerCard(current_chat.crmcustomer_id)"><i class="el-icon-user-solid" style="color: magenta" ></i></a>-->
                  <el-button type="text" title="解绑客户" @click="handleRemoveBindCustomer(current_chat)"><i class="el-icon-user-solid" style="color: magenta" /></el-button>
                </div>

                <el-button v-if="current_chat.crmorder === ''" style="float: right; margin-right: 10px" size="mini" title="绑定订单" @click="handleBindCrmOrder(current_chat)"><i class="el-icon-goods" /></el-button>
                <div v-else>
                  <a title="点击查看订单信息" target="_blank" :href="'https://erp.kikimami.com/#/crm/crmorder?kw=' + current_chat.crmorder.order_no">{{ current_chat.crmorder.order_no }}</a>
                  <el-button type="text" title="解绑订单" @click="handleRemoveBindCrmOrder(current_chat)"><i class="el-icon-s-goods" /></el-button>
                </div>

                <el-button style="float: right; margin-right: 10px" size="mini" @click="hanldeEditChat">编辑</el-button>
                <el-button style="float: right; margin-right: 10px" size="mini" @click="getMessages">刷新</el-button>
                <el-button
                  v-if="aiReplyContent"
                  style="float: right; margin-right: 10px"
                  size="mini"
                  @click="aiReplyDrawerVisible = true"
                >
                  查看AI回复
                </el-button>
              </div>
              <el-main ref="messageList" v-loading="loadingmessage">
                <div v-if="this.total_meesages" class="loading-more">{{ more_notice }}</div>
                <div v-for="msg in messages" :key="msg.id" class="message">
                  <div v-if="msg.message_from === current_config._serialized" class="my-message">
                    <div class="message-body">
                      <div v-if="msg.content_type.includes('audio')">
                        <audio :src="msg.media_url" controls />
                      </div>
                      <div v-else-if="msg.content_type.includes('image')">
                        <el-image style="max-width: 300px; height: auto;" :src="msg.media_url" :preview-src-list="[msg.media_url]" />
                      </div>
                      <div v-else v-html="msg.body" />
                    </div>
                    <div v-if="msg.message_from_name !== msg.message_from" class="message-time">{{ msg.message_from_name }}|{{ msg.message_from }}|{{ msg.message_at }}<a v-if="msg.body_translate === ''" style="font-size: 12px;color:#2f2ff7;" @click="handleAiTranslate(msg, 'Chinese')">翻译</a></div>
                    <div v-else class="message-time">{{ msg.message_from_name }}|{{ msg.message_at }}<a v-if="msg.body_translate === ''" style="font-size: 12px;color:#2f2ff7;" @click="handleAiTranslate(msg, 'Chinese')">翻译</a></div>
                    <div v-if="msg.sending" class="message-status">正在发送...</div>
                  </div>
                  <div v-else class="their-message">
                    <div class="message-body">
                      <div v-if="msg.content_type.includes('audio')">
                        <audio :src="msg.media_url" controls />
                      </div>
                      <div v-else-if="msg.content_type.includes('image')">
                        <el-image style="max-width: 300px; height: auto;" :src="msg.media_url" :preview-src-list="[msg.media_url]" />
                      </div>
                      <div v-else>
                        <div class="original-message" v-html="msg.body" />
                        <div v-if="msg.body_translate" class="translated-message" v-html="msg.body_translate" />
                      </div>
                    </div>
                    <div v-if="msg.message_from_name !== msg.message_from" class="message-time">{{ msg.message_from_name }}|{{ msg.message_from }}|{{ msg.message_at }}<a v-if="msg.body_translate === ''" style="font-size: 12px;color:#2f2ff7;" @click="handleAiTranslate(msg, 'Chinese')">翻译</a></div>
                    <div v-else class="message-time">{{ msg.message_from_name }}|{{ msg.message_at }}<a v-if="msg.body_translate === ''" style="font-size: 12px;color:#2f2ff7;" @click="handleAiTranslate(msg, 'Chinese')">翻译</a></div>

                  </div>
                </div>
              </el-main>
              <el-footer height="250px">
                <el-input v-if="temp.url === ''" v-model="temp.body" type="textarea" :rows="textareaRows" class="textarea-input" @focus="expandTextarea" />
                <el-image v-if="temp.url !== ''" style="height: 100px; width: auto;" :src="temp.url" :preview-src-list="[temp.url]" class="image-preview" />
                <div class="actions">
                  <aireply type="whatsapp_prompts" :chat_id="current_chat.id" @success="handleInsertReplay" />
                  <el-select v-model="translateDirection" size="mini" style="width: 100px; margin-right: 10px;">
                    <el-option label="中到英" value="zh-en" />
                    <el-option label="英到中" value="en-zh" />
                  </el-select>
                  <el-button size="mini" @click="translateAndSend">翻译</el-button>
                  <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
                  <el-button size="mini" type="primary" @click="onSubmit">发送</el-button>
                </div>
              </el-footer>
            </el-container>
          </el-col>
          <el-col :span="6">
            <el-container v-if="customer_temp.id" style="max-width: 320px;">
              <crmcustomerinfocard :customer_id="customer_temp.id" />
            </el-container>
          </el-col>
        </el-row>
      </el-container>
      <crmeditcustomer
        :customer_row="customer_temp"
        doaction="bind"
        :is-visible="addCustomerVisible"
        @bind="bindCustomer"
        @close="addCustomerVisible=false"
      />
      <el-drawer append-to-body :wrapper-closable="false" title="客户信息" :visible.sync="customerInfoCardDialogVisible">
        <crmcustomerinfocard :customer_id="customer_temp.id" />
      </el-drawer>
      <el-dialog append-to-body :title="edit_chat_title" :visible.sync="innerDialogVisible" :close-on-click-modal="false">
        <h3 v-if="crmcustomer__name !== ''">客户:{{ crmcustomer__name }}的询盘订单</h3>
        <el-form :model="chat_temp" label-position="left" label-width="120px">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="chat_temp.nickname" placeholder="对话昵称或者备注名称" />
          </el-form-item>
          <el-form-item label="客户负责人">
            <el-select
              v-model="chat_temp.sales_manager_id"
              :disabled="!sales_manager_editable"
              placeholder="指定处理人"
              filterable
              clearable
            >
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="user.show_name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进状态" prop="follow_status">
            <el-select v-model="chat_temp.follow_status" placeholder="请选择跟进状态">
              <el-option
                v-for="item in follow_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="需要跟进提醒" prop="need_follow">
            <el-switch
              v-model="chat_temp.need_follow"
              active-text="开启提醒"
              inactive-text="关闭提醒"
            />
          </el-form-item>

          <el-form-item v-if="chat_temp.need_follow" label="提醒时间" prop="follow_alert_at">
            <el-date-picker
              v-model="chat_temp.follow_alert_at"
              type="datetime"
              placeholder="选择提醒时间"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="备注" prop="note">
            <el-input
              v-model="chat_temp.note"
              type="textarea"
              :rows="3"
              placeholder="请输入跟进备注"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmEditChat">确 定</el-button>
        </span>
      </el-dialog>
    </el-container>

    <!-- 新增 AI 回复侧边栏 -->
    <el-drawer
      title="AI助手内容"
      :visible.sync="aiReplyDrawerVisible"
      direction="rtl"
      size="30%"
    >
      <iframe :srcdoc="aiReplyContent" class="ai-reply-iframe" style="width: 100%;height: 100%;" />
    </el-drawer>
  </div>
</template>

<script>
import { Get, Post, Put } from '@/api/crm/crmm'
import { Get as GetWhatsappChats, Put as ModifyWhatsappChat } from '@/api/crm/wsch'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { Translate } from '@/api/crm/crmmanage'
import qs from 'qs'
import Crmeditcustomer from './elements/crmeditcustomer'
import Crmcustomerinfocard from './elements/crmcustomerinfocard'
import Crmfilesmanager from '../../components/crmfilesmanager'
import Aireply from './elements/aireply'
import { Post as GetAiContent } from '@/api/cms/openai'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'

export default {
  name: 'Whatsapp',
  components: { Aireply, Crmfilesmanager, Crmcustomerinfocard, Crmeditcustomer },
  data() {
    return {
      follow_status: [],
      orderstatesloading: false,
      orderStates: [],
      query_follow_status: '',
      cascaderValue: '',
      state: '',
      activeTab: 'all', // 新增：当前激活的标签页
      chatLimit: 50,
      current_chats_page: 1,
      crmcustomer__name: '',
      edit_chat_title: '编辑对话',
      innerDialogVisible: false,
      users: [],
      sales_manager_editable: false,
      chat_temp: {
        nickname: '',
        id: '',
        note: '',
        follow_status: '',
        need_follow: false,
        sales_manager_id: '',
        follow_alert_at: '',
        table_name: 'WhatsappChat'
      },
      isMobile: false, // 默认不是移动设备
      drawerVisible: false,
      wc_id: '',
      current_config: {},
      wcconfigs: [],
      translateDirection: 'zh-en', // 翻译方向
      textareaRows: 6,
      temp: {
        body: '',
        url: ''
      },
      listLoading: false,
      total_chats: 0,
      loadingchats: false,
      current_chat: '',
      current_whatsappuser: '',
      whatsappChats: [],
      searchQuery: '', // 用于存储搜索查询
      chat_serialized: '',
      loadingmessage: false,
      messages: [],
      pagesize: 50,
      total_meesages: 0,
      page_list: [],
      temp_messages: [],
      unsendmessages: [],
      more_notice: '向上滚动加载更多消息',
      addCustomerVisible: false,
      customerInfoCardDialogVisible: false,
      chatUpdateInterval: null,
      messageUpdateInterval: null,
      customer_temp: {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [],
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '独立站', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      },
      aiReplyDrawerVisible: false,
      aiReplyContent: ''
    }
  },
  computed: {
    sortedChats() {
      return this.filteredChats.sort((a, b) => {
        // 首先按照置顶状态排序
        if (a.is_pin && !b.is_pin) return -1
        if (!a.is_pin && b.is_pin) return 1
        // 如果置顶状态相同，则按照最后消息时间排序
        return new Date(b.lastmessage_at) - new Date(a.lastmessage_at)
      })
    },
    filteredChats() {
      return this.whatsappChats
      // 取消
      // if (!this.searchQuery) {
      //   return this.whatsappChats;
      // }
      // return this.whatsappChats.filter(chat =>
      //   chat.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      //   chat.nickname.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
      //   chat._serialized.toLowerCase().includes(this.searchQuery.toLowerCase())
      // );
    },
    hasMoreChats() {
      return this.whatsappChats.length < this.total_chats
    },

    remainingChatsCount() {
      return this.total_chats - this.whatsappChats.length
    }
  },
  mounted() {
    this.$nextTick(() => {
      const messageList = this.$refs.messageList.$el
      messageList.addEventListener('scroll', this.handleScroll)
    })
    // 获取 URL 参数并设置 searchQuery
    this.fetchSearchQueryFromURL()
    // 监听路由变化（如果需要）
    this.watchRouteChange()
    this.getWcConfigs()
    this.chatUpdateInterval = setInterval(() => {
      this.getChats() // 调用 getChats 方法
    }, 20000) // 这里的 10000 表示每10秒执行一次，根据需要调整时间间隔
    this.checkIsMobile()
    window.addEventListener('resize', this.checkIsMobile)
    this.handleGetOrderState()
    this.handleFetchGetUsers()
  },
  beforeDestroy() {
    const messageList = this.$refs.messageList.$el
    messageList.removeEventListener('scroll', this.handleScroll)
    if (this.messageUpdateInterval) {
      clearInterval(this.messageUpdateInterval)
    }
    if (this.chatUpdateInterval) {
      clearInterval(this.chatUpdateInterval)
    }
    window.removeEventListener('resize', this.checkIsMobile)
  },
  methods: {
    handleFetchGetUsers() {
      GetUsers(null, qs.stringify({ 'is_active': 1 }))
        .then(response => {
          this.users = response.data.data
        })
    },
    handleAiTranslate(msg, target_language) {
      const prompt = `Please translate the following original text to ${target_language} :
     # Requirements
     1. Maintain the original meaning and tone
     2. Use natural expressions in the target language
     3. Keep any technical terms accurate
     4. Preserve formatting if present
     5. don't include the '<original>' tag in the output

     # Text to translate
     <original>${msg.body}</original>

     # Output format
     Direct translation only, no explanations.`
      this.$notify({
        title: '处理中',
        message: 'AI正在翻译中...',
        type: 'info',
        duration: 0
      })
      GetAiContent({
        prompt,
        engine: 'gpt-4o',
        humanway: false
      }).then(response => {
        this.$notify.closeAll()
        msg.body_translate = response.original_content
        // 修改这个字段
        Put(msg.id, { body_translate: response.data, table_name: 'WhatsappMessage' }).then(response => {
          console.log(response)
        })
      })
    },
    handleGetOrderState() {
      this.orderstatesloading = true
      GetOrderStatus(null, qs.stringify({
        pagesize: 500,
        all: '1',
        page: 1,
        order_by: 'index',
        order_desc: this.order_desc
      })).then(response => {
        this.orderStates = response.data.data.map(item => {
          item.children = item.childrens
          return item
        })
        // 获取 parent_id为空的所有状态
        this.parentOrderStats = this.orderStates.filter(item => !item.parent_id)
        console.log(this.orderStates)
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
      })
    },
    handleTabClick(tab) {
      // 处理标签页切换
      this.activeTab = tab.name
      this.current_chats_page = 1 // 重置页码
      this.whatsappChats = [] // 清空当前聊天列表
      this.getChats() // 重新获取聊天列表
    },
    checkIsMobile() {
      this.isMobile = window.innerWidth <= 768
    },
    handleInsertFile(item) {
      this.temp.url = item.url
    },
    bindCustomer(customer) {
      this.current_whatsappuser.customer = customer
      this.current_whatsappuser.crmcustomer_id = customer.id
      this.current_chat.customer = customer
      // 查询sortedChats修改跟current_chat一样的信息修改customer
      this.whatsappChats = this.whatsappChats.map(chat => {
        if (chat._serialized === this.current_chat._serialized) {
          chat.customer = customer
        }
        return chat
      })
      this.current_whatsappuser.table_name = 'WhatsappUser'
      Put(this.current_whatsappuser.id, this.current_whatsappuser).then(response => {
        // 提示修改成功
        this.$message({
          message: '绑定成功',
          type: 'success'
        })
      })
    },
    scrollmessage() {
      this.$nextTick(() => {
        const messageListElement = this.$refs.messageList.$el
        // 滚动到底部
        messageListElement.scrollTop = messageListElement.scrollHeight
      })
    },
    getWcConfigs() {
      this.listLoading = true
      Get(null, qs.stringify({
        pagesize: 100,
        table_name: 'WhatsappConfig',
        page: 1
      }))
        .then(response => {
          this.wcconfigs = response.data.data
          // 如果获取到,获取chats
          if (this.wcconfigs.length) {
            this.wc_id = this.wcconfigs[0].id
            this.current_config = this.wcconfigs[0]
            this.getChats()
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleChangeState(value) {
      // 获取最后选择的ID
      this.state = value.length > 0 ? value[value.length - 1] : ''
    },
    getChats() {
      if (!this.wc_id) {
        return
      }
      this.loadingchats = true
      GetWhatsappChats(null, qs.stringify({
        kw: this.searchQuery,
        whatsappconfig_id: this.wc_id,
        follow_status: this.query_follow_status,
        crmorder_state_id: this.state,
        pagesize: this.chatLimit,
        order_desc: '1',
        order_by: 'lastmessage_at',
        query_type: this.activeTab === 'unreplied' ? 'unreply' : '',
        page: this.current_chats_page
      }))
        .then(response => {
          const new_data = response.data.data
          this.follow_status = response.data.follow_status
          console.log(this.follow_status)
          this.whatsappChats = [...this.whatsappChats, ...new_data]
          // 根据id字段去掉重复
          this.whatsappChats = this.whatsappChats.filter((item, index, self) =>
            index === self.findIndex((t) => (
              t.id === item.id
            ))
          )
          this.whatsappChats.sort((a, b) => new Date(b.lastmessage_at) - new Date(a.lastmessage_at))
          this.loadingchats = false
          this.total_chats = response.data.total
        }).catch(err => {
          console.log(err)
          this.loadingchats = false
        })
    },
    handelChangeAccount(id) {
      this.whatsappChats = []
      this.current_config = this.wcconfigs.find(item => item.id === id)
      this.current_chats_page = 1
      this.handleGetChat()
    },
    handleLoadMoreChats() {
      this.current_chats_page += 1
      this.getChats()
    },
    handleGetChat() {
      this.current_chats_page = 1
      this.whatsappChats = []
      this.loadingchats = false
      this.getChats()
      // 循环获取所有chat
      // const total_pages = Math.ceil(this.total_chats / this.chatLimit)
      // for (let i = 2; i <= total_pages; i++) {
      //   this.current_chats_page = i
      //   this.getChats()
      // }
      // // 恢复到第一页
      // this.current_chats_page = 1
    },
    handleResetCustom_temp() {
      this.customer_temp = {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [],
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '独立站', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      }
    },
    handleRemoveBindCrmOrder(chat) {
      chat.crmorder_id = ''
      ModifyWhatsappChat(chat.id, { crmorder_id: chat.crmorder_id }).then(response => {
        this.$message({
          message: '解绑订单成功',
          type: 'success'
        })
      }).catch(error => {
        console.error('解绑订单失败:', error)
      })
    },
    handleBindCrmOrder(chat) {
      this.$prompt('请输入订单ID', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        ModifyWhatsappChat(chat.id, { order_no: value }).then(response => {
          this.$message({
            message: '绑定订单成功',
            type: 'success'
          })
        }).catch(error => {
          console.error('绑定订单失败:', error)
          // 如果更新失败，恢复原来的状态
          chat.is_pin = !chat.is_pin
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleBindCustomer() {
      this.handleResetCustom_temp()
      this.customer_temp.whatsapp = this.current_chat._serialized
      this.addCustomerVisible = true
    },
    togglePin(chat) {
      chat.is_pin = !chat.is_pin
      // 更新��务器端的置顶状态
      Put(chat.id, { table_name: 'WhatsappChat', is_pin: chat.is_pin }).then(response => {
        this.$message({
          message: chat.is_pin ? '对话已置顶' : '对话已取消顶',
          type: 'success'
        })
      }).catch(error => {
        console.error('更新置顶状态失败:', error)
        // 如果更新失败，恢复原来的状态
        chat.is_pin = !chat.is_pin
      })
    },
    handleShowCustomerCard(id) {
      this.customer_temp.id = id
      this.customerInfoCardDialogVisible = true
    },
    getLatestMessages(scrol_to_end = false) {
      Get(null, qs.stringify({
        whatsappchat_id: this.current_chat.id,
        pagesize: this.pagesize,
        order_by: 'message_at',
        order_desc: '1',
        table_name: 'WhatsappMessage',
        page: 1
      }))
        .then(response => {
          this.total_meesages = response.data.total
          // 检查消息是否存在,不在列表中则插入，根据id
          response.data.data.forEach(item => {
            if (!this.temp_messages.find(msg => msg.id === item.id)) {
              this.temp_messages.push(item)
            }
          })
          // 按照message_at排序,倒叙
          this.temp_messages.sort((a, b) => {
            return new Date(a.message_at) - new Date(b.message_at)
          })
          if (this.temp_messages.length >= this.total_meesages) {
            this.more_notice = '没有更多消息了'
          }
          this.getUnsentMessages(scrol_to_end)
        }).catch(err => {
          console.log(err)
        })
    },
    getMessages(scroll_to_end = false) {
      // 计算pagesize
      if (!this.current_chat.id) {
        this.$notify({
          title: '错误',
          message: '请选择一个聊天',
          type: 'error'
        })
        return
      }
      // 如果当前页面大于total_meesages,则不再获取
      if (this.total_meesages !== 0 && this.messages.length >= this.total_meesages) {
        this.more_notice = '没有更多消息了'
        return
      }
      // page_list里面的id增加1
      let current_page = this.page_list.length > 0 ? Math.max(...this.page_list) : 0
      current_page += 1
      // let current_page = this.messages.length > 0 ? Math.ceil(this.messages.length / this.pagesize) : 0;
      // current_page += 1
      console.log(this.messages.length, current_page)
      this.more_notice = '消息加载中'
      Get(null, qs.stringify({
        whatsappchat_id: this.current_chat.id,
        pagesize: this.pagesize,
        order_by: 'message_at',
        order_desc: '1',
        table_name: 'WhatsappMessage',
        page: current_page
      }))
        .then(response => {
          // 如果page_list里面没有当前current_page,添加
          if (!this.page_list.includes(current_page)) {
            this.page_list.push(current_page)
          }
          console.log(this.page_list)
          // this.temp_messages = response.data.data
          this.total_meesages = response.data.total
          // 检查消息是否存在,不在列表中则插入，根据id
          response.data.data.forEach(item => {
            if (!this.temp_messages.find(msg => msg.id === item.id)) {
              this.temp_messages.push(item)
            }
          })
          // 按照message_at排序,倒叙
          this.temp_messages.sort((a, b) => {
            return new Date(a.message_at) - new Date(b.message_at)
          })
          if (this.temp_messages.length >= this.total_meesages) {
            this.more_notice = '没有更多消息了'
          }
          this.getUnsentMessages(scroll_to_end)
        }).catch(err => {
          console.log(err)
        })
    },
    handleInsertReplay(replay) {
      // this.temp.body = replay
      this.setAiReplyContent(replay)

      // 更新current_chat的operation_suggestion
      this.current_chat.operation_suggestion = replay

      // 更新服务器端的operation_suggestion
      Put(this.current_chat.id, {
        table_name: 'WhatsappChat',
        operation_suggestion: replay
      }).then(response => {
        console.log('operation_suggestion updated')
      }).catch(error => {
        console.error('更新operation_suggestion失败:', error)
      })

      this.aiReplyDrawerVisible = true
    },
    setAiReplyContent(content) {
      // 为 iframe 内容添加基本的 HTML 结构和样式
      this.aiReplyContent = `
        <html>
          <head>
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                padding: 10px;
              }
              p { margin: 0 0 10px; }
              h1, h2, h3, h4, h5, h6 { margin: 10px 0; }
              pre {
                background-color: #f4f4f4;
                padding: 10px;
                border-radius: 4px;
                overflow-x: auto;
              }
              code {
                font-family: 'Courier New', Courier, monospace;
                background-color: #f0f0f0;
                padding: 2px 4px;
                border-radius: 3px;
              }
            </style>
          </head>
          <body>${content}</body>
        </html>
      `
    },
    expandTextarea() {
      this.textareaRows = 6 // 点击时设置行数为6
      this.scrollmessage()
    },
    handleRemoveBindCustomer(row) {
      // 先确认是否要执行解绑操作
      this.$confirm('此操作将解除客户' + row._serialized + '绑定, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ModifyWhatsappChat(row.id, { crmcustomer_id: null }).then(response => {
          // 提示修改成功
          this.$message({
            message: '解绑成功',
            type: 'success'
          })
          this.current_chat.crmcustomer_id = null
          this.current_chat.customer = ''
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解绑'
        })
      })
    },
    hanldeEditChat() {
      this.chat_temp.id = this.current_chat.id
      this.chat_temp.nickname = this.current_chat.nickname
      this.edit_chat_title = '编辑对话' + this.current_chat.name
      this.chat_temp.follow_status = this.current_chat.follow_status
      this.chat_temp.sales_manager_id = this.current_chat.sales_manager_id
      this.sales_manager_editable = this.current_chat.sales_manager_id === null || this.current_chat.sales_manager_id === ''
      if (this.$store.getters.roles.includes('sales_manager') || this.$store.getters.roles.includes('admin')) {
        this.sales_manager_editable = true
      }
      this.chat_temp.need_follow = this.current_chat.need_follow
      this.chat_temp.follow_alert_at = this.current_chat.follow_alert_at
      this.chat_temp.note = this.current_chat.note
      this.innerDialogVisible = true
    },
    handleConfirmEditChat() {
      this.chat_temp.table_name = 'WhatsappChat'
      Put(this.chat_temp.id, this.chat_temp).then(response => {
        this.innerDialogVisible = false
      })
    },
    handleChangChat(chat) {
      // 清除之前的定时器（如果存在）
      this.drawerVisible = false
      if (this.messageUpdateInterval) {
        clearInterval(this.messageUpdateInterval)
      }

      // 查找whatsappchat中_serialized = chat 的对象
      this.current_chat = this.whatsappChats.find(item => item._serialized === chat)

      // 如果current_chat有operation_suggestion,则设置aiReplyContent
      if (this.current_chat.operation_suggestion) {
        this.setAiReplyContent(this.current_chat.operation_suggestion)
      } else {
        this.aiReplyContent = ''
      }

      Put(this.current_chat.id, { table_name: 'WhatsappChat', need_refresh: true }).then(response => {
        console.log(response)
      })
      this.messages = []
      this.temp_messages = []
      this.page_list = []
      this.getLatestMessages(true)
      this.current_whatsappuser = this.current_chat.whatsappusers[0]
      if (this.current_chat.crmcustomer_id) {
        this.customer_temp.id = this.current_chat.crmcustomer_id
      } else {
        this.customer_temp.id = ''
      }
      // 设置新的定时器以周期性获取聊天信息
      this.messageUpdateInterval = setInterval(() => {
        this.getLatestMessages(false) // 调用获取消息的方法
      }, 10000) // 每5秒获取一次，可以根据需要调整时间间隔
      // 3 秒钟之后执行this.scrollmessage()
      setTimeout(() => {
        this.scrollmessage()
      }, 1000)
    },
    getUnsentMessages(scroll_to_end = false) {
      Get(null, qs.stringify({
        whatsappchat_id: this.current_chat.id,
        is_send: false,
        pagesize: 100,
        table_name: 'WhatsappSendMessage',
        page: 1
      }))
        .then(response => {
          this.unsendmessages = response.data.data
          console.log(this.unsendmessages)
          // 构造消息放在messages中
          this.unsendmessages.forEach(item => {
            // 如果不存在词条消息，则添加
            const tempMessage = {
              body: item.body,
              _serialized: 'new_' + item.id,
              message_from: 'me',
              content_type: 'text',
              message_at: item.create_at,
              sending: true
            }
            // 如果 temp_messags存在_serialized 则不插入
            if (!this.temp_messages.find(msg => msg._serialized === tempMessage._serialized)) {
              this.temp_messages.push(tempMessage)
            }
          })
          this.messages = this.temp_messages
          // if (scroll_to_end) {
          //   this.scrollmessage()
          // }
        }).catch(err => {
          console.log(err)
          this.messages = this.temp_messages
        })
    },
    translateMessage(msg) {
      Translate({
        text: msg.body,
        source_language: 'en',
        target_language: 'zh'
      })
        .then(response => {
          msg.body_translate = response.data
          // 修改这个字段
          Put(msg.id, { body_translate: response.data, table_name: 'WhatsappMessage' }).then(response => {
            console.log(response)
          })
        })
    },
    translateAndSend() {
      // 如果没有输入内容，不进行翻译
      if (!this.temp.body) {
        return
      }
      // 使用百度翻译API进行翻译
      Translate({
        text: this.temp.body,
        source_language: this.translateDirection.split('-')[0],
        target_language: this.translateDirection.split('-')[1]
      })
        .then(response => {
          // 将翻译结果添加到输入框中
          this.temp.body = response.data
        })
    },
    onSubmit() {
      console.log(this.temp.body)
      this.temp.whatsappconfig_id = this.wc_id
      this.temp._serialized = this.chat_serialized
      this.temp.whatsappchat_id = this.current_chat.id
      this.temp.table_name = 'WhatsappSendMessage'
      Post(this.temp
      ).then(response => {
        this.getMessages()
        const tempMessage = {
          body: this.temp.body,
          message_from: 'me', // 假设当前用户的serialized
          content_type: 'text', // 假设消息类型为文本
          message_at: new Date().toISOString(), // 使用当前时间作为消息时间
          sending: true // 标记消息为正在发送
        }
        this.messages.push(tempMessage)
        this.temp.body = ''
      })
    },
    loadMoreMessages() {
      this.getMessages(false)
    },
    handleScroll() {
      const messageList = this.$refs.messageList.$el
      if (messageList.scrollTop === 0) {
        this.loadMoreMessages()
      }
    },
    fetchSearchQueryFromURL() {
      // 检查是否使用 Vue Router
      if (this.$route && this.$route.query) {
        const searchParam = this.$route.query.search
        if (searchParam) {
          this.searchQuery = searchParam
          this.handleGetChat()
        }
      } else {
        // 如果没有使用 Vue Router，可以使用 window.location.search
        const urlParams = new URLSearchParams(window.location.search)
        const searchParam = urlParams.get('search')
        if (searchParam) {
          this.searchQuery = searchParam
          this.handleGetChat()
        }
      }
    },
    watchRouteChange() {
      this.$watch('$route.query', (newQuery) => {
        const newSearch = newQuery.search || ''
        if (newSearch !== this.searchQuery) {
          this.searchQuery = newSearch
          this.handleGetChat()
        }
      }, { immediate: true, deep: true })
    }
  }
}
</script>

<style scoped>
.chat-sidebar-wrapper {
  height: calc(100vh - 60px); /* Adjust based on your header height */
  overflow-y: auto;
}

.chat-sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.chat-list {
  display: flex;
  flex-direction: column;
}

.chat-item {
  border-bottom: 1px solid #e6e6e6;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.chat-item:hover {
  background-color: #f0f2f5;
}

.chat-item.active {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.chat-item-content {
  display: flex;
  align-items: stretch;
  height: 70px; /* Fixed height for each chat item */
}

.chat-avatar-wrapper {
  width: 70px;
  height: 70px;
  overflow: hidden;
}

.chat-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 5px;
  overflow: hidden;
}

.chat-name {
  font-size: 12px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-last-message {
  font-size: 8px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  padding: 10px;
  min-width: 70px;
}

.chat-time {
  font-size: 12px;
  color: #999;
}

.unread-badge {
  margin-top: 5px;
}

.translated-message {
  color: #007bff; /* 使用不同颜色（例如蓝色）来表示翻译文本 */
  font-style: italic; /* 可以选择使用斜体来进一步区分 */
}

.footer-content {
  display: flex;
  justify-content: space-between; /* 确保内容在两侧 */
  align-items: flex-start; /* 对齐到顶部 */
  width: 100%; /* 确保容器宽度为100% */
}

.image-preview {
  max-width: 50%; /* 或其他合适的比例，确保图片不会太大 */
}

.actions {
  display: flex;
  align-items: flex-end; /* 确保按钮垂直居中 */
  justify-content: flex-end;
  gap: 10px; /* 按钮之间的间距 */
  flex-grow: 1;
}

.textarea-input {
  width: 100%; /* 确保输入框宽度自适应 */
  margin-bottom: 10px; /* 与下方内容的间距 */
}

.loading-more {
  text-align: center;
  color: #999;
  margin-bottom: 10px;
}

.ai-reply-content {
  padding: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.custom-drawer-content :deep(p) {
  margin: 0.5em 0;
  line-height: 1.5;
}

.custom-drawer-content :deep(h1) {
  font-size: 1.8em;
  margin: 0.8em 0 0.4em;
}

.custom-drawer-content :deep(h2) {
  font-size: 1.6em;
  margin: 0.7em 0 0.35em;
}

.custom-drawer-content :deep(h3) {
  font-size: 1.4em;
  margin: 0.6em 0 0.3em;
}

.custom-drawer-content :deep(h4) {
  font-size: 1.2em;
  margin: 0.5em 0 0.25em;
}

.custom-drawer-content :deep(h5) {
  font-size: 1.1em;
  margin: 0.4em 0 0.2em;
}

.custom-drawer-content :deep(h6) {
  font-size: 1em;
  margin: 0.3em 0 0.15em;
}

.custom-drawer-content :deep(ul),
.custom-drawer-content :deep(ol) {
  margin: 0.5em 0;
  padding-left: 1.5em;
}

.custom-drawer-content :deep(li) {
  margin: 0.2em 0;
}

.custom-drawer-content :deep(pre) {
  margin: 0.5em 0;
  padding: 0.5em;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow-x: auto;
}

.custom-drawer-content :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: #f0f0f0;
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.el-menu-item {
  border-bottom: 1px solid #ebeef5; /* 浅灰色边线 */
}

.chat-header {
  display: flex;
  justify-content: space-between; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  width: 100%;
  margin: 10px;
}

.el-main {
  max-height: 465px; /* 或根据需要设置其他高度 */
  overflow-y: auto;
  background-color: #fff;
  color: #333;
  text-align: center;
  border-top: 1px solid #dbdbdb; /* 上边框 */
  border-right: 1px solid #dbdbdb; /* 右边框 */
}

/* Add your styles here */
.aside-menu {
  height: 100%;
  border-right: 0;
}

/* 添加消息样式 */
.message {
  display: flex;
  margin-bottom: 10px;
}

.my-message {
  margin-left: auto;
  padding: 10px;
  background-color: #dcf8c6; /* 浅绿色，表示自己的消息 */
  border-radius: 5px;
  text-align: right;
}

.their-message {
  margin-right: auto;
  padding: 10px;
  background-color: #fff; /* 白色，表示对方的消息 */
  border-radius: 5px;
  text-align: left;
}

.message-body {
  margin-bottom: 5px;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}

.el-aside {
  background-color: #fff;
  border: 1px solid #dbdbdb; /* 灰色边框 */
  color: #333;
  padding-top: 20px;
  padding-left: 10px;
  height: 650px;
  line-height: 250px;
}

body > .el-container {
  padding-right: 10px;
}

@media (max-width: 768px) {
  .el-container,
  .el-header,
  .chat-header {
    flex-direction: column;
    align-items: stretch; /* 让子元素宽度自适应 */
  }

  .chat-header,
  .message,
  .el-footer {
    padding: 10px; /* 为了在手机上更好地显示，增加内边距 */
  }

  .el-main {
    max-height: calc(100vh - 200px); /* 调整主内容区域的最大高度 */
    overflow-y: auto; /* 允许纵向滚动 */
  }

  .el-footer {
    height: auto; /* 自适应高度 */
  }

  .el-input,
  .el-button {
    width: 100%; /* 让输入框和按钮在手机上占满可用宽度 */
    margin: 5px 0; /* 添加一些外边距以分隔元素 */
  }

  .message {
    flex-direction: column; /* 让消息在手机上垂直排列 */
  }
  .show-more-btn {
  width: 100%;
  margin-top: 10px;
  }
}
.pin-button {
  padding: 2px;
  font-size: 16px;
}

.el-icon-pin {
  color: #909399;
}

.el-icon-pin.is-pinned {
  color: #409EFF;
}

.pin-label {
  font-size: 10px;
  background-color: #409EFF;
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  margin-left: 5px;
}

.el-tabs {
  margin-bottom: 10px;
}

.ai-reply-content {
  padding: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.custom-drawer-content :deep(p) {
  margin: 0.5em 0;
  line-height: 1.5;
}

.custom-drawer-content :deep(h1) {
  font-size: 1.8em;
  margin: 0.8em 0 0.4em;
}

.custom-drawer-content :deep(h2) {
  font-size: 1.6em;
  margin: 0.7em 0 0.35em;
}

.custom-drawer-content :deep(h3) {
  font-size: 1.4em;
  margin: 0.6em 0 0.3em;
}

.custom-drawer-content :deep(h4) {
  font-size: 1.2em;
  margin: 0.5em 0 0.25em;
}

.custom-drawer-content :deep(h5) {
  font-size: 1.1em;
  margin: 0.4em 0 0.2em;
}

.custom-drawer-content :deep(h6) {
  font-size: 1em;
  margin: 0.3em 0 0.15em;
}

.custom-drawer-content :deep(ul),
.custom-drawer-content :deep(ol) {
  margin: 0.5em 0;
  padding-left: 1.5em;
}

.custom-drawer-content :deep(li) {
  margin: 0.2em 0;
}

.custom-drawer-content :deep(pre) {
  margin: 0.5em 0;
  padding: 0.5em;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow-x: auto;
}

.custom-drawer-content :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: #f0f0f0;
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

</style>
